package com.hz.ruoyiequipment.equipment.service.impl;

import com.hz.ruoyiequipment.equipment.domain.AgrEquipmentFertigation;
import com.hz.ruoyiequipment.equipment.mapper.WafEquipmentMapper;
import com.ruoyi.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author: zjk
 * @Date: 2025/3/22 14:41
 * @Description: 水肥机地块灌溉状态 Redis
 */

@Service
@Slf4j
public class SfPlotsdRedisService {
    @Autowired
    private RedisService redisService;
@Autowired
   private WafEquipmentMapper wafEquipmentMapper;


    // Redis Key 前缀
    private static final String THRESHOLD_KEY_PREFIX = "agr_equipment:sf_eqId:";

//     初始化 Redis 数据
    @PostConstruct
    public void initRedisData() {
        // 1. 删除 Redis 中所有相关数据
        deleteAllThresholdRules();
        List<AgrEquipmentFertigation> allPlotsId = wafEquipmentMapper.listPlotsStatus();
        for (AgrEquipmentFertigation sfPlot : allPlotsId) {
            String key = THRESHOLD_KEY_PREFIX + sfPlot.getEquipmentId();
            List<Long> plotsId = sfPlot.getPlotsId();
            for (int i = 0; i < plotsId.size(); i++) {
                redisService.setCacheMapValue(key,  plotsId.get(i).toString(), 0);
            }

        }

        log.info("水肥机地块灌溉状态信息已加载到 Redis");
    }
    /**
     * 删除 Redis 中所有相关数据
     */
    private void deleteAllThresholdRules() {
        // 获取所有匹配 THRESHOLD_KEY_PREFIX 的键
        Set<String> keys = (Set<String>) redisService.keys(THRESHOLD_KEY_PREFIX + "*");

        if (keys != null && !keys.isEmpty()) {
            // 批量删除
            redisService.deleteObject(keys);
            log.info("已删除 {} 条旧地块灌溉规则", keys.size());
        } else {
            log.info("未找到需要删除的旧地块灌溉规则");
        }
    }

    // 从 Redis 获取水肥机地块灌溉状态
    public Map<String, Integer> getThresholdRules(Long equipmentId) {
        String key = THRESHOLD_KEY_PREFIX + equipmentId;
        log.info("获取Redis水肥机地块灌溉状态, 设备id{}, {}", equipmentId,redisService.getCacheMap(key));
        System.out.println(redisService.getCacheMap(key).toString());
        return redisService.getCacheMap(key);
    }

    // 更新 Redis 中的水肥机地块灌溉状态
    public void updateThresholdRules(Long equipmentId, String plotsId, Integer status) {
        String key = THRESHOLD_KEY_PREFIX + equipmentId;
        redisService.setCacheMapValue(key, plotsId, status);
        log.info("Redis 中的水肥机地块灌溉状态已更新，设备ID: {}, 地块ID: {},状态: {}", equipmentId, plotsId,status);
    }

    // 删除 Redis 中的水肥机地块灌溉状态
    public void deleteThresholdRules(Long equipmentId, String plotsId) {
        String key = THRESHOLD_KEY_PREFIX + equipmentId;
        redisService.deleteCacheMapValue(key, plotsId);
        log.info("Redis 中的水肥机地块灌溉状态已删除，设备ID: {}, 地块ID: {}", equipmentId, plotsId);
    }
}
